package com.stone.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stone.common.result.BaseResponse;
import com.stone.common.result.ErrorCode;
import com.stone.common.result.ResultUtils;
import com.stone.user.model.entity.User;
import com.stone.user.service.UserService;
import com.stone.user.utils.JwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/hello")
    public String helloWorld(){
        System.out.println("hello world");
        return "hello world";
    }

    @GetMapping("/get/byId")
    public BaseResponse<User> getUserById(Long userId){
        return ResultUtils.success(userService.getById(userId));
    }

    @GetMapping("/list/page")
    public BaseResponse<List<User>> listUserPage(int current , int pageSize){
        Page<User> userPage = userService.page(new Page<>(current ,pageSize));
        return ResultUtils.success(userPage.getRecords());
    }

    @GetMapping("/list/page/byUserName")
    public BaseResponse<List<User>> listUserPageByUserName(int current , int pageSize , String userName){
        Page<User> userPage = userService.page(new Page<>(current ,pageSize) , new QueryWrapper<User>().lambda().eq(User::getUserName , userName));
        return ResultUtils.success(userPage.getRecords());
    }

    @PostMapping("/add")
    public BaseResponse<Long> addUser(@RequestBody User user){
        userService.save(user);
        return ResultUtils.success(user.getId());
    }

    @DeleteMapping("/delete/byId")
    public void deleteUserById(Long userId){
        userService.removeById(userId);
    }

    @PutMapping("/update/byId")
    public void updateUserById(@RequestBody User user){
        userService.updateById(user);
    }

    @GetMapping("/login")
    public BaseResponse<String> login(String userAccount , String userPassword){
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda().eq(User::getUserAccount, userAccount).eq(User::getUserPassword, userPassword);
        User user = userService.getOne(queryWrapper);
        if(user!=null){
            // 查询到了用户，代表登录成功，需要给前端返回token
            String token = JwtUtil.createToken(userAccount, user.getId().toString());
            System.out.println(token);
            return ResultUtils.success(token);
        }
        return ResultUtils.error(ErrorCode.LOGIN_ERROR , "账号或者密码错误");
    }
}
